<script setup lang="ts">
  import useLoading from '@/hooks/loading';
  import { useI18n } from 'vue-i18n';
  import { computed, reactive, ref } from 'vue';
  import {
    Message,
    PaginationProps,
    TableColumnData,
    TableRowSelection,
  } from '@arco-design/web-vue';
  import {
    archivedArticles,
    publishArticles,
    removeArticle,
    selectPageArticle,
  } from '@/api/article';
  import { getCategoryList } from '@/api/category';
  import AddModal from '@/views/blog/article/components/add-modal.vue';

  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const articleStatusFieldNames = { value: 'value', label: 'label' };
  const articleStatusOptions = ref([
    {
      label: '全部',
      value: -1,
    },
    {
      label: '草稿',
      value: 0,
    },
    {
      label: '已发布',
      value: 1,
    },
    {
      label: '已归档',
      value: 2,
    },
  ]);
  const addModalRef = ref();
  const categoryFieldNames = { value: 'id', label: 'name' };
  const scroll = {
    x: 5000,
    y: 'calc(100vh - 311px)',
  };

  // 修改选择行相关的定义
  const selectedRowKeys = ref<(string | number)[]>([]);

  const rowSelection: TableRowSelection = {
    type: 'checkbox',
    showCheckedAll: true,
  };

  type SizeProps = 'mini' | 'small' | 'medium' | 'large';
  const size = ref<SizeProps>('medium');

  const handleSelectDensity = (
    val: string | number | Record<string, any> | undefined,
    e: Event,
  ) => {
    size.value = val as SizeProps;
  };

  const densityList = computed(() => [
    {
      name: t('searchTable.size.mini'),
      value: 'mini',
    },
    {
      name: t('searchTable.size.small'),
      value: 'small',
    },
    {
      name: t('searchTable.size.medium'),
      value: 'medium',
    },
    {
      name: t('searchTable.size.large'),
      value: 'large',
    },
  ]);

  // 文章信息列表
  const columns: TableColumnData[] = [
    {
      title: '封面',
      dataIndex: 'coverImage',
      align: 'center',
      slotName: 'coverImage',
    },
    {
      title: '标题',
      dataIndex: 'title',
      align: 'center',
    },
    {
      title: '摘要',
      dataIndex: 'summary',
      align: 'center',
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '作者',
      dataIndex: 'author',
      align: 'center',
    },
    {
      title: '分类',
      dataIndex: 'categoryName',
      align: 'center',
    },
    {
      title: '标签',
      dataIndex: 'tags',
      align: 'center',
      slotName: 'tags',
    },
    {
      title: 'SEO标题',
      dataIndex: 'seoTitle',
      align: 'center',
    },
    {
      title: 'SEO描述',
      dataIndex: 'seoDescription',
      align: 'center',
      ellipsis: true,
      tooltip: true,
    },
    {
      title: 'SEO关键词',
      dataIndex: 'seoKeywords',
      align: 'center',
    },
    {
      title: '别名',
      dataIndex: 'slug',
      align: 'center',
    },
    {
      title: '置顶',
      dataIndex: 'isSticky',
      align: 'center',
      slotName: 'isSticky',
    },
    {
      title: '允许评论',
      dataIndex: 'allowComments',
      align: 'center',
      slotName: 'allowComments',
    },
    {
      title: '发布时间',
      dataIndex: 'publishTime',
      align: 'center',
    },
    {
      title: '来源',
      dataIndex: 'source',
      align: 'center',
      slotName: 'source',
    },
    {
      title: '外部链接',
      dataIndex: 'externalLink',
      align: 'center',
    },
    {
      title: '热度值',
      dataIndex: 'hotness',
      align: 'center',
    },
    {
      title: '推荐',
      dataIndex: 'isRecommended',
      align: 'center',
      slotName: 'isRecommended',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      align: 'center',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      align: 'center',
    },
    {
      title: '浏览次数',
      dataIndex: 'views',
      align: 'center',
    },
    {
      title: '点赞次数',
      dataIndex: 'likes',
      align: 'center',
    },
    {
      title: '评论次数',
      dataIndex: 'commentsCount',
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      slotName: 'status',
      fixed: 'right',
      width: 100,
    },
    {
      title: '操作',
      align: 'center',
      slotName: 'operation',
      fixed: 'right',
      width: 200,
    },
  ];

  const articleList = ref([]);
  const categoryList = ref([]);

  const params = ref({
    pageNo: 1,
    pageSize: 10,
    title: '',
    status: -1,
    category: '',
  });

  const pagination = reactive<PaginationProps>({
    showTotal: true,
    showPageSize: true,
    pageSizeOptions: [5, 10, 50, 100],
  });

  const getArticleList = async () => {
    setLoading(true);
    try {
      const result = await selectPageArticle(params.value);
      articleList.value = result.data.list;
      pagination.total = result.data.total;
      pagination.current = params.value.pageNo;
      pagination.pageSize = params.value.pageSize;
    } finally {
      setLoading(false);
    }
  };
  getArticleList();

  // 查询分类
  const getCateList = async () => {
    const result = await getCategoryList();
    categoryList.value = result.data;
  };
  getCateList();

  // 查询
  const handleSearch = () => {
    params.value.pageNo = 1;
    getArticleList();
  };

  // 重置
  const handleReset = () => {
    params.value.pageNo = 1;
    params.value.title = '';
    params.value.status = -1;
    params.value.category = '';
    getArticleList();
  };

  // 刷新
  const handleReFresh = () => {
    getArticleList();
  };

  // 切换页面
  const handlePageNoChange = (pageNo: number) => {
    params.value.pageNo = pageNo;
    getArticleList();
  };

  // 变更页数数量
  const handlePageSizeChange = (pageSize: number) => {
    params.value.pageSize = pageSize;
    getArticleList();
  };

  // 删除
  const handleDelete = async (id: number) => {
    const result = await removeArticle([id]);
    Message.success(result.data);
    // 重新查询
    if (articleList.value.length === 1 && params.value.pageNo !== 1) {
      params.value.pageNo -= 1;
    }
    await getArticleList();
  };

  // 保存成功回调函数
  const handleSaveSuccess = () => {
    getArticleList();
  };

  const handlePublish = async () => {
    if (selectedRowKeys.value.length > 0) {
      const result = await publishArticles(selectedRowKeys.value as number[]);
      Message.success(result.data);
      await getArticleList();
    } else {
      Message.error('请至少选中一行数据！');
    }
  };

  const handleArchived = async () => {
    if (selectedRowKeys.value.length > 0) {
      const result = await archivedArticles(selectedRowKeys.value as number[]);
      Message.success(result.data);
      await getArticleList();
    } else {
      Message.error('请至少选中一行数据！');
    }
  };

  const handleOpen = () => {
    addModalRef.value.handleOpen();
  };

  const handleEdit = (id: number) => {
    addModalRef.value.handleEdit(id);
  };
</script>

<template>
  <a-row>
    <a-col :flex="1">
      <a-form
        :model="params"
        label-align="left"
        :label-col-props="{ span: 6 }"
        layout="inline"
        :wrapper-col-props="{ span: 18 }"
      >
        <a-form-item field="title" label="标题：" label-col-flex="70px">
          <a-input v-model="params.title" placeholder="请输入标题" />
        </a-form-item>
        <a-form-item field="category" label="分类：" label-col-flex="70px">
          <a-select
            v-model="params.category"
            :options="categoryList"
            :field-names="categoryFieldNames"
            placeholder="请选择文章分类"
            :style="{ width: '200px' }"
          />
        </a-form-item>
        <a-form-item field="status" label="状态：" label-col-flex="70px">
          <a-select
            v-model="params.status"
            :options="articleStatusOptions"
            :field-names="articleStatusFieldNames"
            placeholder="请选择文章状态"
            :style="{ width: '120px' }"
          />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button
              v-permission="'system:role:list'"
              type="primary"
              @click="handleSearch"
            >
              <template #icon>
                <icon-search />
              </template>
              {{ $t('searchTable.form.search') }}
            </a-button>
            <a-button type="primary" @click="handleReset">
              <template #icon>
                <icon-refresh />
              </template>
              {{ $t('searchTable.form.reset') }}
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-col>
  </a-row>
  <a-divider style="margin-top: 10px; margin-bottom: 16px" />
  <a-row style="margin-bottom: 16px">
    <a-col :span="12">
      <a-space>
        <a-button
          v-permission="'blog:article:add'"
          type="primary"
          @click="handleOpen"
        >
          <template #icon>
            <icon-plus />
          </template>
          {{ $t('searchTable.operation.create') }}
        </a-button>
        <a-button
          v-permission="'blog:article:publish'"
          type="primary"
          :disabled="selectedRowKeys.length === 0"
          @click="handlePublish"
        >
          <template #icon>
            <icon-pushpin />
          </template>
          {{ $t('searchTable.operation.publish') }}
        </a-button>
        <a-button
          v-permission="'blog:article:archived'"
          type="primary"
          :disabled="selectedRowKeys.length === 0"
          @click="handleArchived"
        >
          <template #icon>
            <icon-storage />
          </template>
          {{ $t('searchTable.operation.archived') }}
        </a-button>
      </a-space>
    </a-col>
    <a-col
      :span="12"
      style="display: flex; align-items: center; justify-content: end"
    >
      <a-space :size="12">
        <a-button>
          <template #icon>
            <icon-download />
          </template>
          {{ $t('searchTable.operation.download') }}
        </a-button>
        <a-tooltip
          :content="$t('searchTable.actions.refresh')"
          @click="handleReFresh"
        >
          <div class="action-icon">
            <icon-refresh size="18" />
          </div>
        </a-tooltip>
        <a-dropdown @select="handleSelectDensity">
          <a-tooltip :content="$t('searchTable.actions.density')">
            <div class="action-icon">
              <icon-line-height size="18" />
            </div>
          </a-tooltip>
          <template #content>
            <a-doption
              v-for="item in densityList"
              :key="item.value"
              :value="item.value"
              :class="{ active: item.value === size }"
            >
              <span>{{ item.name }}</span>
            </a-doption>
          </template>
        </a-dropdown>
      </a-space>
    </a-col>
  </a-row>
  <a-row style="flex: 1">
    <a-col :span="24">
      <a-table
        v-model:selected-keys="selectedRowKeys"
        row-key="id"
        :loading="loading"
        :columns="columns"
        :data="articleList"
        :scroll="scroll"
        :bordered="false"
        :size="size"
        :pagination="pagination"
        page-position="br"
        :row-selection="rowSelection"
        @page-change="handlePageNoChange"
        @page-size-change="handlePageSizeChange"
      >
        <template #coverImage="{ record }">
          <a-image
            class="action-icon"
            width="100px"
            height="80px"
            style="border-radius: 0.375rem"
            :show-loader="true"
            :src="record.coverImage"
            preview
          ></a-image>
        </template>
        <template #tags="{ record }">
          <a-space>
            <a-tag v-for="tag in record.tags" :key="tag" color="orange">
              {{ tag }}
            </a-tag>
          </a-space>
        </template>
        <template #isSticky="{ record }">
          <a-tag :color="record.isSticky === 1 ? 'green' : 'red'">
            {{ record.isSticky === 1 ? '是' : '否' }}
          </a-tag>
        </template>
        <template #allowComments="{ record }">
          <a-tag :color="record.allowComments === 1 ? 'green' : 'red'">
            {{ record.allowComments === 1 ? '是' : '否' }}
          </a-tag>
        </template>
        <template #source="{ record }">
          <a-tag :color="record.source === 0 ? 'green' : 'blue'">
            {{ record.source === 0 ? '原创' : '转载' }}
          </a-tag>
        </template>
        <template #isRecommended="{ record }">
          <a-tag :color="record.isRecommended === 1 ? 'green' : 'red'">
            {{ record.isRecommended === 1 ? '是' : '否' }}
          </a-tag>
        </template>
        <template #status="{ record }">
          <a-tag v-if="record.status === '草稿'" color="red">
            {{ record.status }}
          </a-tag>
          <a-tag v-else-if="record.status === '已发布'" color="green">
            {{ record.status }}
          </a-tag>
          <a-tag v-else-if="record.status === '已归档'" color="blue">
            {{ record.status }}
          </a-tag>
        </template>
        <template #operation="{ record }">
          <a-button
            v-permission="'system:role:edit'"
            type="text"
            @click="handleEdit(record.id)"
            >{{ $t('searchTable.operation.edit') }}
          </a-button>
          <a-popconfirm
            :content="$t('modal.operation.tips')"
            @ok="handleDelete(record.id)"
          >
            <a-button v-permission="'blog:article:remove'" type="text"
              >{{ $t('searchTable.operation.remove') }}
            </a-button>
          </a-popconfirm>
        </template>
      </a-table>
    </a-col>
  </a-row>
  <add-modal ref="addModalRef" @save-success="handleSaveSuccess"></add-modal>
</template>

<style scoped lang="less">
  .action-icon {
    cursor: pointer;
  }
</style>
